<template>
  <div>
    <div class="ccui-navigation">
      <!-- 面包屑 -->
      <el-button
        size="mini"
        type="primary-icon-medium"
        icon="icon-ccui-return"
        @click="handleBack"
        >返回</el-button
      >
      <div class="ccui-navigation-divider" />
      <!-- 面包屑 -->
      <el-breadcrumb
        class="ccui-navigation-crumbs-container"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
          :to="{ path: $store.getters.getBreadcrumb('level1').path }"
          >{{ $store.getters.getBreadcrumb("level1").name }}</el-breadcrumb-item
        >
        <el-breadcrumb-item
          :to="{
            path: '/settlement-management/transportation-maintenance-approval'
          }"
          >结算管理</el-breadcrumb-item
        >
        <el-breadcrumb-item
          :to="{
            path: '/settlement-management/transportation-maintenance-approval'
          }"
          >运输结算管理</el-breadcrumb-item
        >
        <el-breadcrumb-item
          :to="{
            path: breadUrl
          }"
          >{{ breadItem }}</el-breadcrumb-item
        >
        <el-breadcrumb-item>
          <span class="ccui-curr-crumb"
            >查看 {{ settlementForm.settlementName }}</span
          >
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="ccui-app-container-detail">
      <div class="ccui-app-container-detail-body">
        <el-tabs
          v-model="activeName"
          @tab-click="handleClick"
          class="el-tabs__customize"
        >
          <el-tab-pane label="基本信息" name="first">
            <baseInfoCheck
              ref="bassettlement-checkeInfo"
              :detail="detailInfo"
              :myId="myId"
              :settlement-form="settlementForm"
            />
          </el-tab-pane>

          <el-tab-pane label="结算单明细" name="second">
            <keep-alive>
              <financeInfoCheck
                ref="financeInfo"
                :settlementList="settlementList"
                :detail="detailInfo"
              />
            </keep-alive>
          </el-tab-pane>

          <el-tab-pane label="附件" name="fouth">
            <keep-alive>
              <upload-table
                v-if="isRange"
                ref="contractAppendix"
                state="detail"
                v-model="fileList"
              />
            </keep-alive>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!--  底部导航栏及签名导出  -->
    <bottomGuide
      v-if="isTrue"
      busiType="103"
      exportMethod="get"
      methodGetPageType="exportSettleTrans"
      :approvalStatus="
        ['5', '22'].includes(settlementForm.settlementStatus)
          ? 'approvaled'
          : ''
      "
      :curPageId="$route.params.id"
      :businessCode="businessCode"
      @handleBack="handleBack"
    >
      <template slot="start">
        <li>
          <el-button
            v-if="
              settlementForm.supplierBillStatus == 3 &&
              ['2', '4', '6'].includes(settlementForm.settlementStatus)
            "
            type="bottom"
            icon="icon-ccui-export"
            @click="openReturnDialog"
            >退回供应商
          </el-button>
        </li>
        <li>
          <el-button
            v-if="
              settlementForm.supplierBillStatus == 3 &&
              ['2', '4', '6'].includes(settlementForm.settlementStatus)
            "
            type="bottom"
            icon="icon-ccui-export"
            @click="submitSettlement"
            >保存并提交
          </el-button>
        </li>
      </template>
    </bottomGuide>

    <returnDialog ref="returnDialog" @getValue="getValue" />
  </div>
</template>

<script>
import jsList from "../js";
import baseInfoCheck from "./baseInfoCheck";
import financeInfoCheck from "./financeInfoCheck";
import {
  getSettlementById,
  sendBackSupplierSettlement,
  editTransSettlement,
  getUserInfo
} from "../api/transportation-approval";
import { addUrlPerFix } from "@/basa/utils";
import publicComponent from "@/basa/components/public";
import returnDialog from "@/app/transportation-settlement/transportation-maintenance-approval/components/returnDialog";
// import Mixin from "../mixins";
export default {
  // mixins: [Mixin],
  inject: ["reload"],
  props: {
    state: {
      type: String,
      default: ""
    }
  },
  components: {
    UploadTable: publicComponent.uploadInfo3,
    baseInfoCheck,
    financeInfoCheck,
    returnDialog,
    bottomGuide: publicComponent.bottomGuide
  },
  data() {
    return {
      businessCode: "",
      settlementForm: {
        pcConcId: "", // 基础合同id
        scConcId: "", // 结算申请单id
        materialName: "", // 合同名称
        materialCode: "", // 合同编号
        partyAName: "", // 合同甲方
        partyBId: "", // 合同乙方id
        partyBName: "", // 合同乙方
        materialName1: "", //供应商
        taxRatePercent: "", // 税率
        nowTotalContractPriceIncludeTax: "", // 合同金额（含税）
        settleTotalAmtIncludeTax: "", // 开累结算金额（含税）
        payedTotalAmtIncludeTax: "", // 开累支付金额
        settleTotalUnpaidAmt: "", // 开累结算未支付金额
        contractBalance: "", // 合同余额（含税）
        settlementNum: "", // 结算单编号
        settlementPeriod: "", // 结算期次
        currentSettlePayAmtIncludeTax: "", // 本期支付金额
        currentSettleAmtIncludeTax: "", // 本期结算金额（含税）
        currentSettleUnpayAmtIncludeTax: "", // 本期结算未支付金额（含税）
        paymentNum: "", // 支付单编号
        compiler: "", // 编制人
        compilerId: "", // 编制人id
        paymentApplyDate: "", // 支付申请日期
        remarks: "", // 备注,
        settlements: ""
      },
      settlementList: [],
      fileList: [],
      jsList,
      breadcrumbLastItem: "结算单",
      activeName: "first",
      isTrue: false,
      detailInfo: {},
      isFocus: "baseInfo",
      uploadList: [],
      myId: "",
      tabBtn: [
        { label: "基本信息", value: "baseInfo" },
        { label: "财务信息", value: "financeInfo" },
        { label: "采购清单", value: "purchaseList" }
      ],
      summaryArr: ["subContractorsName"],
      tableTheadOptions: [
        {
          label: "合同编号",
          prop: "subContractName",
          width1: 120
        },
        {
          label: "合同名称",
          prop: "subContractorsName"
        }
      ],
      oneLineTableData: [
        { subContractName: 1, subContractorsName: 1 },
        { subContractName: 1, subContractorsName: 1 },
        { subContractName: 1, subContractorsName: 1 },
        { subContractName: 1, subContractorsName: 1 }
      ],
      arr1: [
        { id: 1, name: "aa" },
        { id: 2, name: "bb" },
        { id: 3, name: "cc" }
      ],
      arr2: [
        { id: 1, name: "aa" },
        { id: 2, name: "bb" }
      ],
      a: [],
      isTz: "",
      breadItem: "",
      breadUrl: "",
      isRange: false
    };
  },
  created() {
    this.isTz = this.$route.params.tz;
    if (this.isTz == 1) {
      this.breadItem = "结算单台账";
      this.breadUrl = "/settlement-management/transportation-standing-book";
    } else {
      this.breadItem = "结算单维护";
      this.breadUrl =
        "/settlement-management/transportation-maintenance-approval";
    }

    let a = [...this.arr1];
    for (let i = 0; i < this.arr1.length; i++) {
      let flag = false;
      for (let j = 0; j < this.arr2.length; j++) {
        if (this.arr1[i].id === this.arr2[j].id) flag = true;
      }
      if (flag)
        a.splice(
          a.findIndex(_ => _.id === this.arr1[i].id),
          1
        );
    }
    this.myId = this.$route.params.id;
    this.init();
    this.getUserInfo();
  },
  activated() {
    this.init();
    this.getUserInfo();
    this.activeName = "first";
  },
  deactivated() {
    // this.nextIsTrue();
    this.isTrue = false;
  },
  methods: {
    // 获取详情
    getUserInfo() {
      getUserInfo(
        addUrlPerFix(process.env.VUE_APP_BASEP_URL) + "/apis/basap/getUserInfo",
        {}
      ).then(res => {
        this.settlementForm.reportUsername = res.data.data.userInfo.name;
      });
    },
    // 处理附件入参
    handleFilesParams() {
      let gistUploadIds = [],
        otherUploadIds = [];

      this.fileList.map((e, i) => {
        if (e.fileType == 51) {
          gistUploadIds.push({
            fileDesc: e.fileDesc,
            sn: i,
            uploadId: e.uploadId,
            uploadTime: e.uploadTime || e.createTime
          });
        } else {
          otherUploadIds.push({
            fileDesc: e.fileDesc,
            sn: i,
            uploadId: e.uploadId,
            uploadTime: e.uploadTime || e.createTime
          });
        }
      });
      return {
        gistUploadIds: gistUploadIds,
        otherUploadIds: otherUploadIds
      };
    },
    // sort 排序
    handleSort(property) {
      return function (a, b) {
        return a[property] - b[property];
      };
    },
    init() {
      // const { id } = this.$route.params;
      const data = {
        id: this.myId,
        isShowPageLoading: true
      };
      getSettlementById(data)
        .then(res => {
          this.businessCode = res.data.data.settlementBO.settlementCode;
          this.settlementForm = res.data.data.settlementBO;
          this.settlementForm.settlements =
            this.settlementForm.settlementStart +
            "到" +
            this.settlementForm.settlementEnd;
          this.settlementForm.contractMoney = this.settlementForm.contractMoney
            ? this.settlementForm.contractMoney.toFixed(2)
            : "";
          res.data.data.gistFiles.map(e => {
            e.fileType = 51;
            e.fileTypeName = "结算依据";
          });
          res.data.data.otherFiles.map(e => {
            e.fileType = 52;
            e.fileTypeName = "其他";
          });
          this.fileList = [
            ...res.data.data.gistFiles,
            ...res.data.data.otherFiles
          ];
          this.fileList.sort(this.handleSort("sn"));
          this.isRange = true;
          // 含税金额为0时，该行不显示
          this.settlementList = res.data.data.settlementBOList;
          this.settlementList.forEach(row => {
            row.unTransportCount = row.unTransportCount.toFixed(3);
            row.settlementCount = row.settlementCount
              ? row.settlementCount.toFixed(3)
              : "";
            row.unitPriceWithTax = row.unitPriceWithTax
              ? row.unitPriceWithTax.toFixed(2)
              : "";
            row.unitPriceWithoutTax = row.unitPriceWithoutTax
              ? row.unitPriceWithoutTax.toFixed(2)
              : "";
            row.moneyWithTax = row.moneyWithTax
              ? row.moneyWithTax.toFixed(2)
              : "";
            row.moneyWithoutTax = row.moneyWithoutTax
              ? row.moneyWithoutTax.toFixed(2)
              : "";
          });
          // .filter(_item => {
          //   return _item.moneyWithTax != 0;
          //   // _item => !temp.has(_item.moneyWithTax)
          // });
          this.isTrue = true;
          console.log(this.settlementList, "-----------------------------");
        })
        .catch(e => {});
      // this.getRegisterInfo();
    },
    handleClick(tab, event) {
      console.log(tab, event, this.activeName);
      this.activeName = tab.name;
    },
    // 退回操作
    openReturnDialog() {
      this.$refs["returnDialog"].visibleDialog = true;
    },
    // 退回弹框确定调用接口
    getValue(val) {
      let params = {
        id: +this.$route.params.id,
        supplierSendBackReason: val,
        isShowPageLoading: true
      };
      sendBackSupplierSettlement(params).then(res => {
        this.$message({
          type: "success",
          message: res.data.message
        });
        this.handleBack();
      });
    },
    // 保存并提交操作
    submitSettlement() {
      this.settlementForm.billSource = "10";
      let params = {
        settlementBO: this.settlementForm,
        settlementBOList: this.settlementList,
        gistUploadIds: this.handleFilesParams().gistUploadIds,
        otherUploadIds: this.handleFilesParams().otherUploadIds,
        operType: 1,
        isShowPageLoading: true
      };
      editTransSettlement(params).then(res => {
        this.$message({
          type: "success",
          message: "保存并提交成功"
        });
        this.handleBack();
      });
    },
    handleBack() {
      this.$router.push(
        sessionStorage.getItem("fromPath") ||
          "settlement-management/transportation-maintenance-approval/transportation-maintenance-unsubmitted"
      );
      this.reload();
    }
  }
};
</script>
<style lang="scss" scoped>
/deep/ .el-tabs__customize {
  padding-bottom: 50px;
}
</style>
